#include <string.h>
#include "lib.h"


//-------------------------------------------------------------------------
//
//-------------------------------------------------------------------------
void buffer_Push(BUFFER *pBuf, U8 *pData, U32 nLength)
{
	U32 nResultLen, nNewAllocLen;
	nResultLen = pBuf->nLen + nLength;
	nNewAllocLen = (nResultLen + BUFFER_BLOCK_MASK) & ~BUFFER_BLOCK_MASK;
	if (pBuf->nLen == 0) {
		if (pBuf->p != NULL) {
			mem_Free(&pBuf->p);
		}
		pBuf->p = mem_Malloc(nNewAllocLen);
	} else {
		if (((pBuf->nLen + BUFFER_BLOCK_MASK) & ~BUFFER_BLOCK_MASK) != nNewAllocLen) {
			mem_Realloc(&pBuf->p, nNewAllocLen);
		}
	}
	memcpy(pBuf->p + pBuf->nLen, pData, nLength);
	pBuf->nLen = nResultLen;
}

//-------------------------------------------------------------------------
//
//-------------------------------------------------------------------------
void buffer_Cut(BUFFER *pBuf, U32 nOffset, U32 nLength)
{
	U32 nNewAllocLen;
	nNewAllocLen = (nLength + BUFFER_BLOCK_MASK) & ~BUFFER_BLOCK_MASK;
	if (nLength) {
		memmove(pBuf->p, pBuf->p + nOffset, nLength);
		if (((pBuf->nLen + BUFFER_BLOCK_MASK) & ~BUFFER_BLOCK_MASK) != nNewAllocLen) {
			mem_Realloc(&pBuf->p, nNewAllocLen);
		}
		pBuf->nLen = nLength;
	} else {
		buffer_Free(pBuf);
	}
}

//-------------------------------------------------------------------------
//
//-------------------------------------------------------------------------
void buffer_Free(BUFFER *pBuf)
{
	mem_Free(&pBuf->p);
	memset(pBuf, 0, sizeof(BUFFER));
}
